package com.example.java_chatroom.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class TextWebSocketController extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在webSocket建立连接之后，spring会自动调用这个方法
        log.info("webSocket建立连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //这个方法会在webSocket收到消息之后，被自动调用
        log.info("webSocket成功接收消息："+message.toString());
        //将信息返回
        //session里面就已经记录了通信双方是谁了(及通信双方)
        session.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接出现异常，被自动调用
        log.info("webSocket建立连接出现异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常关闭之后，自动调用
        log.info("webSocket连接关闭成功");
    }
}
